import { _decorator, Component, Node, Prefab, instantiate, } from 'cc';
import { CellGroup } from './CellGroup';
import { CellGroupConfig } from './Types';
import { cellGroups } from './CellGroupData';
const { ccclass, property } = _decorator;

@ccclass('CellGroupContainer')
export class CellGroupContainer extends Component {
    @property(Prefab)
    cellGroupPrefab: Prefab = null;

    @property(Prefab)
    cellPrefab: Prefab = null;

    private pickedCellGroup: CellGroup | null = null;

    private initCellGroups() {
        const startX = -350 + 64;
        const startY = 128;
        const spacing = 140;

        cellGroups.forEach((groupConfig, index) => {
            const cellGroup = this.createCellGroup(groupConfig);
            const posX = startX + index * spacing;
            const posY = startY;
            cellGroup.node.setPosition(posX, posY);
            this.node.addChild(cellGroup.node);
        });
    }

    private createCellGroup(config: CellGroupConfig): CellGroup {
        const node = instantiate(this.cellGroupPrefab);
        const cellGroup = node.getComponent(CellGroup);
        cellGroup.init(config, this.cellPrefab);
        return cellGroup;
    }

    public isAnyCellGroupPickedUp(): boolean {
        return this.pickedCellGroup !== null;
    }

    public setPickedCellGroup(cellGroup: CellGroup | null) {
        if (this.pickedCellGroup && this.pickedCellGroup !== cellGroup) {
            this.pickedCellGroup.putDown();
        }
        this.pickedCellGroup = cellGroup;
    }

    public clearCellGroups() {
        this.node.removeAllChildren();
        this.pickedCellGroup = null;
    }

    public reinitialize() {
        this.clearCellGroups();
        this.initCellGroups();
    }

    public rotatePickedCellGroup(): void {
        if (this.pickedCellGroup && this.pickedCellGroup.node && this.pickedCellGroup.node.isValid) {
            this.pickedCellGroup.rotate();
        }
    }

    public getPickedCellGroup(): CellGroup | null {
        return this.pickedCellGroup;
    }
} 